package com.geek.factory.security;

import com.geek.factory.service.SmsService;
import com.geek.factory.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

/**
 * 手机号验证码认证提供者
 */
@Component
public class PhoneCodeAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PhoneCodeAuthenticationToken authenticationToken = (PhoneCodeAuthenticationToken) authentication;

        String phone = authenticationToken.getPhone();
        String code = authenticationToken.getCode();

        // 验证验证码
        if (!smsService.checkCode(phone, code)) {
            throw new BadCredentialsException("验证码错误");
        }

        // 通过手机号加载用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(phone);

        // 创建认证成功的token
        PhoneCodeAuthenticationToken authenticatedToken = new PhoneCodeAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        //authenticatedToken.setDetails(authenticationToken.getDetails());

        return authenticatedToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return PhoneCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}